package com.tonyodev.fetchapp.fetch2okhttp;

import ohos.aafwk.ability.delegation.AbilityDelegatorRegistry;
import ohos.app.Context;

import com.tonyodev.fetch2.Request;
import com.tonyodev.fetch2.database.DownloadInfo;
import com.tonyodev.fetch2.util.FetchUtils;
import com.tonyodev.fetch2.util.TypeConverterExtensions;
import com.tonyodev.fetch2core.Downloader;
import com.tonyodev.fetch2core.FetchCoreUtils;
import com.tonyodev.fetch2core.InterruptMonitor;
import com.tonyodev.fetch2okhttp.OkHttpDownloader;

import java.io.IOException;

import junit.framework.TestCase;

public class OkHttpDownloaderTest extends TestCase {

    private Context appContext;
    private Downloader downloader;

    public void setUp() throws Exception {
        super.setUp();

        appContext = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext();
        downloader = new OkHttpDownloader(Downloader.FileDownloaderType.PARALLEL);
    }

    public void tearDown() throws Exception {
    }

    public void testExecute() throws IOException {
        final Request request = getTestRequest();
        final DownloadInfo downloadInfo = TypeConverterExtensions.toDownloadInfo(request, new DownloadInfo());

        Downloader.ServerRequest openingRequest;
        if (downloader.getHeadRequestMethodSupported(FetchUtils.getRequestForDownload(downloadInfo))) {
            openingRequest = FetchUtils.getRequestForDownload(downloadInfo, FetchCoreUtils.HEAD_REQUEST_METHOD);
        } else {
            openingRequest = FetchUtils.getRequestForDownload(downloadInfo);
        }

        Downloader.Response response = downloader.execute(openingRequest, interruptMonitor);
        assertEquals(response.isSuccessful(), true);

    }

    private InterruptMonitor interruptMonitor = new InterruptMonitor() {
        @Override
        public boolean isInterrupted() {
            return true;
        }
    };

    public Request getTestRequest() {
        final String url = "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4";
        final String file = appContext.getFilesDir() + "/testFolder/bunny" +
                System.nanoTime() + " .mp4";
        return new Request(url, file);
    }
}